import axios from 'axios'
import type { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios'
import type { HYRequestConfig, HYRequestIntereptors } from './type'
import 'element-plus/es/components/loading/style/css'
import { ElLoading } from 'element-plus'
const DEFAULT_LOADING = true

class HYRequest<T = any> {
  instance: AxiosInstance
  interceptors?: HYRequestIntereptors
  showLoading?: boolean
  loading?: any
  constructor(config: HYRequestConfig<T>) {
    this.instance = axios.create(config)
    this.showLoading =
      config.showLoading === undefined ? DEFAULT_LOADING : config.showLoading

    this.interceptors = config.interceptors
    this.instance.interceptors.request.use(
      this.interceptors?.requestInterceptor,
      this.interceptors?.requestInterceptorCatch
    )
    this.instance.interceptors.response.use(
      this.interceptors?.responseInterceptor,
      this.interceptors?.responseInterceptorCatch
    )

    this.instance.interceptors.request.use(
      (config: AxiosRequestConfig) => {
        if (this.showLoading) {
          this.loading = ElLoading.service({
            lock: true,
            text: 'Loading',
            background: 'rgba(0, 0, 0, 0.2)',
            fullscreen: true
          })
        }
        return config
      },
      (error: any) => {
        console.log(error)
      }
    )

    this.instance.interceptors.response.use(
      (res: AxiosResponse<T>) => {
        this.loading?.close()
        return res.data
      },
      (error: any) => {
        this.loading?.close()
        return error
      }
    )
  }

  request<T = any>(config: HYRequestConfig): Promise<T> {
    return new Promise((resolve, reject) => {
      if (config.showLoading === false) {
        this.showLoading = config.showLoading
      }
      this.instance
        .request<T, T>(config)
        .then((res) => {
          resolve(res)
        })
        .catch((err) => {
          reject(err)
          return err
        })
        .finally(() => {
          this.showLoading = DEFAULT_LOADING
        })
    })
  }
  get<T>(config: HYRequestConfig): Promise<T> {
    return this.request<T>({
      method: 'GET',
      ...config
    })
  }
  post<T>(config: HYRequestConfig): Promise<T> {
    return this.request<T>({
      method: 'POST',
      ...config
    })
  }
  delete<T>(config: HYRequestConfig): Promise<T> {
    return this.request<T>({
      method: 'DELETE',
      ...config
    })
  }
  patch<T>(config: HYRequestConfig): Promise<T> {
    return this.request<T>({
      method: 'PATCH',
      ...config
    })
  }
}

export default HYRequest
